<template>
  <div>
    <el-row>
        <el-col :span="8">
            <!-- 试卷基本信息 -->
            <div class="paper_info_box">
                <div>试卷名称：{{ paper.paperName }}</div>
                <div>总分: {{ paper.paperScore }}</div>
                <div>时长: {{ totalTime }} 分钟</div>
                <el-divider></el-divider>
                <div>
                    <el-row>
                        <el-col :span="6" v-for="(item, index) in problemsChoose" :key="index">
                            <el-button circle :class="{ btn_base: true, problem_finish: item.isFinish }">{{ (index + 1) }}</el-button>
                        </el-col>
                    </el-row>
                </div>
                <el-divider></el-divider>
                <div>剩余时间：{{ formatTime }} 分钟 {{ formatSecond }} 秒</div>
                <el-divider></el-divider>
                <div><el-button type="primary" :disabled="isParsePaper" @click="submitPaper">提交试卷</el-button></div>
            </div>
        </el-col>
        <el-col :span="16">
            <!-- 试题内容 -->
            <div class="paper_problems">
                <!-- 暂时只考虑了选择题 -->
                <div class="problem_type_title">选择题</div>
                <div v-for="(item, problemOrder) in problems" :key="problemOrder">
                    <div class="problem_title">{{ (problemOrder + 1) + "、" + item.problem.problemDesc }}</div>
                    <div>
                        <ul>
                            <li :class="{answer_title: true, answer_selected: answer.isSelected}" 
                                @click="recordAnswer(problemOrder, answerOrder)" 
                                v-for="(answer, answerOrder) in item.answers" 
                                :key="answerOrder">
                                {{ answer.answer }}
                            </li>
                        </ul>
                    </div>
                    <div v-if="isParsePaper"> 正确答案：{{parseCorrectAnswer(item.answers)}}</div>
                </div>
            </div>
        </el-col>
    </el-row>
    <el-dialog
        title="提示"
        :visible.sync="computeScoreWindow"
        width="30%"
        >
        <div style="margin-bottom: 15px">得分：{{ score }}</div>
        <el-row>
            <el-col :span="16"><el-button type="primary" @click="showPracticeAnswer">查看详情</el-button></el-col>
            <el-col :span="8"><el-button type="primary" @click="practiceRepeat">再次练习</el-button></el-col>
        </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {getConfig, parseUserAnswer} from '@/api/system/system.js'
export default {
    data() {
        return {
            problems: [
                {
                    title: '一问三不知，指的是哪三不知？',
                    type: 1,
                    answers: [
                        {
                            answerId: 7,
                            title: '起因-经过-结果',
                            isSelected: false
                        },
                        {
                            answerId: 8,
                            title: '老子-孟子-墨子',
                            isSelected:  false
                        },
                        {
                            answerId: 9,
                            title: '四书-五艺-春秋',
                            isSelected: false
                        }
                    ]
                },
                {
                    title: '一问三不知，指的是哪三不知？',
                    type: 2,
                    answers: [
                        {
                            answerId: 10,
                            title: '起因-经过-结果',
                            isSelected: false
                        },
                        {
                            answerId: 11,
                            title: '老子-孟子-墨子',
                            isSelected: false
                        },
                        {
                            answerId: 12,
                            title: '四书-五艺-春秋',
                            isSelected: false
                        }
                    ]
                }
            ],
            currentPractice: {},
            userAnswer: [],
            oneAnswer: 10,
            paper: {},
            baseAnswer: 'answer_title',
            selectAnswer: '',
            problemsChoose: [],
            totalTime: 0,
            formatTime: 0,
            formatSecond: 0,
            timerId: '',
            problemTypes: [],
            score: 0,
            computeScoreWindow: false,
            isParsePaper: false
        }
    },
    async mounted() {
        this.currentPractice = JSON.parse(this.$store.state.currentPractice)
        this.paper = this.currentPractice.paper
        this.problems = this.currentPractice.problems
        const {data: problemTypes} = await getConfig({codeType: 'PROBLEM_TYPE', codeValue: ''})
        if (problemTypes.code === 200) {
            this.problemTypes = problemTypes.data.cache
        }
        // 获取当前试卷
        this.problems.forEach((item, index) => {
            var obj = {}
            obj.order = index
            obj.isFinish = false
            this.problemsChoose.push(obj)
        })
        this.parseTime(this.paper.limitTime)
        // 开启定时器，倒计时开始
        this.timerId = setInterval(() => {
            if (this.isParsePaper) {
                clearInterval(this.timerId)
            }
            if (this.formatTime < 0) {
                clearInterval(this.timerId)
                this.submitPaper()
            }
            if (this.formatSecond === 0) {
                this.formatTime = this.formatTime - 1
                this.formatSecond = 59
            } else {
                this.formatSecond = this.formatSecond - 1
            }
        }, 1000)
    },
    destroyed() {
        clearInterval(this.timerId)
    },
    computed: {
        parseProblemDesc() {
            return function(problem, problemOrder) {
                const tempProblem = { ...problem }
                const tempOrder = problemOrder
                return (tempOrder + 1) + "、" + tempProblem.problemDesc
            }
        },
        parseCorrectAnswer() {
            return function(answers) {
                let correct = ''
                answers.forEach(item => {
                    if (item.isRight === 1) {
                        correct = item.answer
                    }
                })
                return correct
            }
        }
    },
    methods: {
        recordAnswer(problemOrder, answerOrder) {
            // 记录用户选择的答案,还没考虑多选
            // 记录方式：以问题为下标，answer为value存一个数组
            
            // 改变选项样式
            this.changeSelectedStyle(problemOrder, answerOrder)
            // 同步左侧题号状态
            this.syncUseranswer()
        },
        showPracticeAnswer() {
            this.isParsePaper = true
            this.computeScoreWindow = false
        },
        practiceRepeat() {
            //
        },
        changeSelectedStyle(problemOrder, answerOrder) {
            // todo 选择答案
            // type：题型，多选-单选
            var problem = this.problems[problemOrder]
            var answers = problem.answers
            if (problem.problem.problemType === 1) {
                // 单选
                answers.forEach(answer => {
                    answer.isSelected = false
                })
            }
            answers[answerOrder].isSelected = !answers[answerOrder].isSelected
            this.userAnswer[problemOrder] = []
            var obj = {
                problemInstId: '',
                userAnswer: []
            }
            obj.problemInstId = problem.problem.problemInstId
            answers.forEach(item => {
                if (item.isSelected) {
                    obj.userAnswer.push(item.answerId) 
                    this.userAnswer[problemOrder].push(JSON.stringify(obj))
                }
            })
            problem.answers = answers
            this.problems[problemOrder] = problem
        },
        async submitPaper() {
            // 检查试卷是否完成
            const totalProblems = this.problemsChoose.length
            let finishProblems = 0
            this.userAnswer.forEach(item => {
                if (item && item.length > 0) {
                    finishProblems = finishProblems + 1
                }
            })
            if (finishProblems < totalProblems) {
                return this.$message.success('还有未提交的试题')
            }
            // 提交试卷，包括试卷实例编号以及用户答案
            let params = {}
            params.paperInstId = this.currentPractice.paperInst.paperInstId
            params.userAnswer = JSON.stringify(this.userAnswer)
            const { data: res } = await parseUserAnswer(params)
            if (res.code === 200) {
                this.score = res.data.score
                this.computeScoreWindow = true
            }
        },
        syncUseranswer() {
            this.userAnswer.forEach((item, index) => {
                if (item && item.length > 0) {
                    this.problemsChoose[index].isFinish = true
                } else {
                    this.problemsChoose[index].isFinish = false
                }
            })
        },
        parseTime(time) {
            this.formatTime = time / 1000 / 60
            this.totalTime = this.formatTime
        }
        
    }
}
</script>

<style lang="css" scoped>
.paper_info_box {
    width: 240px;
    height: 500px;
    margin-top: 30px;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 10px;
}
.paper_problems {
    width: 100%;
    margin-right: 10px;
    margin-top: 30px;
    padding: 10px;  
    border: 1px solid #ccc;
}
.problem_finish {
    background: skyblue;
    color: white;
}
.btn_base {
    width: 36px;
    height: 36px;
    border-radius: 18px;
    text-align: center;
}
.problem_type_title {
    font-size: 16px;
    font-weight: 700;
    margin-bottom: 3px;
}
.problem_title {
    font-size: 14px;
    margin-bottom: 3px;
}
.answer_title {
    font-size: 12px;
    height: 25px;
    line-height: 25px;
    text-decoration: none;
}
.answer_title:hover {
    cursor: pointer;
}
.answer_selected {
    color: skyblue;
    font-size: 14px;
}
</style>